#-*-coding:utf-8-*-
__author__ = 'toriycn'
import json
import  time
import threading
import traceback

from client import redishelper
from client.conf import settings
from client.plugins import  plugin_api
from client import  LogUtil


class MonitorClient(object):

    def __init__(self):
        self.r = redishelper.RedisHelper(settings.RedisServer, settings.RedisPort, settings.RedisPubChannel, settings.RedisSubChannel)
        self.ip = settings.ClientIp
        self.host_config = self.get_host_config()


    def start(self):
        self.handle()

    def get_host_config(self):
        config_key = "HostConfig::%s"% self.ip
        config = self.r.get(config_key)
        if config:
            config = json.loads(str(config,"utf-8"))
        return config

    def handle(self):

        #处理一条从服务器过来的数据
        pub = self.r.subscribe()
        t1 = threading.Thread(target=self.call_receive_service,args=(pub,))
        t1.setDaemon(True)
        t1.start()
        if self.host_config :
            while True:
                for service,val in self.host_config.items():
                    if len(val) <3: #确保第一次可以执行
                        self.host_config[service].append(0)
                    plugin_name,interval,last_run_time = val
                    if time.time() - last_run_time < interval:
                        pass
                    else:
                        self.host_config[service][2] = time.time()
                        t2 = threading.Thread(target=self.call_plugin,args=(service,plugin_name))
                        t2.setDaemon(True)
                        t2.start()



                time.sleep(1)
        else:
            LogUtil.logger.error("Cannot get host config")

    def call_receive_service(self,pub):
        while True:
            try:
                 #处理一条从服务器过来的数据
                 host_service_data = pub.parse_response()
                 host_service_data = json.loads(str(host_service_data[2],encoding="utf-8"))
            except:
               traceback.print_exc()


    def call_plugin(self,service_name,plugin_name):
        func = getattr(plugin_api,plugin_name)
        service_datas = {}
        service_datas['data'] = func()

        service_datas['host'] = self.ip
        service_datas['service'] = service_name
        self.r.public(json.dumps(service_datas))
